import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { DownOutlined, UpOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import {
  Row,
  Col,
  Card,
  Button,
  Tabs,
  DatePicker,
  Dropdown,
  Menu,
  Divider,
  message,
  Select,
} from 'antd';
import router from 'umi/router';
import moment from 'moment';
import queryString from 'query-string';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import Customer from '../../components/Customer'; // 客户名称
import DictCode from '../../components/DictCode';
import TextOverFlow from '../../components/TextOverFlow';
import CustOrSupp from './CustOrSupp'; // 客户/供应商名称模糊查询
import CustSuppCont from './CustSuppCont'; // 客户/供应商合同模糊查询
import RefundModal from './RefundModal'; // 退票弹框组件
import Authorized from '@/utils/Authorized';
import { checkPermissions } from '@/utils/authority';
import styles from '@/utils/utils.less';
import HOCSelect from '@/components/AntDesign/Select';

const FormItem = Form.Item;
const { TabPane } = Tabs;
const { RangePicker } = DatePicker;
const { Option } = Select;
@connect(({ invoice, loading, login: { systemList }, addemprec }) => ({
  pageData: invoice.pageData,
  loading: loading.models.invoice,
  tabList: invoice.tabList,
  expandForm: invoice.expandForm,
  activeKey: invoice.activeKey,
  formFieldsValue: invoice.formFieldsValue,
  systemList,
  supplyList: addemprec.supplyList,
  valuesArr: invoice.valuesArr,
}))
@Form.create()
class TableList extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      selectedRows: [],
      selectedRowKeys: [],
      formValues: {},
      modalVisible: false,
      loadingFlag: false,
      sysCode: 1,
      invApplyId: null,
    };

    this.tableSearchLayout = {
      labelCol: { md: { span: 7 } },
      wrapperCol: { md: { span: 17 } },
    };
  }

  componentDidMount() {
    const { dispatch, systemList, params } = this.props;
    const { sysCode } = systemList.filter(item => item.isSelected)[0];
    this.setState({ sysCode });
    dispatch({
      type: 'invbycustsupp/updateModelData',
      payload: {
        formFieldsValue: {
          costType: '1',
        },
        selectedRows: [],
        selectedRowKeys: [],
      },
    });
    if (sysCode !== 1) {
      // 获取签约方
      dispatch({
        type: 'addemprec/fetchSupplyList',
        payload: { name: null, ...params },
      });
    }
    this.getInitialList();
  }

  getInitialList = () => {
    const {
      pageData: { pagination },
      dispatch,
      location,
      formFieldsValue,
      activeKey,
    } = this.props;
    const tempActiveKey = queryString.parse(location.search).activeKey || activeKey;
    if (location.queryParam) {
      dispatch({
        type: 'invoice/updateModalData',
        payload: { formFieldsValue: location.queryParam, expandForm: true },
      });
    }
    dispatch({
      type: 'invoice/updateModalData',
      payload: {
        activeKey: tempActiveKey,
      },
    });
    this.searchList(
      this.processFormData({ ...formFieldsValue }),
      tempActiveKey,
      pagination.current,
      pagination.pageSize
    );
  };

  // 点击查询按钮
  searchBtnList = activeKey => {
    const { form, valuesArr, dispatch } = this.props;
    form.validateFieldsAndScroll([...valuesArr], (err, values) => {
      if (!err) {
        dispatch({
          type: 'invoice/updateModalData',
          payload: {
            formFieldsValue: values,
            activeKey,
          },
        });
        this.searchList(this.processFormData(values), activeKey);
      }
    });
  };

  // 查询
  searchList = (
    formFieldsValue,
    activeKey = '1',
    currentPage = 1,
    pageSize = 10,
    isClear = true
  ) => {
    if (isClear) {
      this.setState({ selectedRows: [], selectedRowKeys: [] });
    }
    const { dispatch } = this.props;
    const pagerArg = { currentPage, pageSize };
    const values = {
      ...formFieldsValue,
      pagerArg,
    };

    dispatch({
      type: 'invoice/updateModalData',
      payload: {
        values,
      },
    });

    if (activeKey === '1') {
      dispatch({
        type: 'invoice/fetchInvRecordList',
        payload: {
          ...values,
        },
      });
    } else {
      dispatch({
        type: 'invoice/fetchInvRuleList',
        payload: values,
      });
    }

    this.setState({
      formValues: values,
    });
  };

  // 处理form数据
  processFormData = fieldsValue => {
    const formFieldsValue = {};
    const tempFieldsValue = fieldsValue;
    Object.keys(tempFieldsValue).forEach(key => {
      if (key === 'applyTime') {
        formFieldsValue.creStartDate =
          (tempFieldsValue.applyTime &&
            tempFieldsValue.applyTime[0] &&
            tempFieldsValue.applyTime[0].format('YYYY-MM-DD')) ||
          null;
        formFieldsValue.creEndDate =
          (tempFieldsValue.applyTime &&
            tempFieldsValue.applyTime[1] &&
            tempFieldsValue.applyTime[1].format('YYYY-MM-DD')) ||
          null;
      }
      if (tempFieldsValue[key] && tempFieldsValue[key].key) {
        formFieldsValue[key] =
          tempFieldsValue[key].key === undefined ? null : tempFieldsValue[key].key;
      } else {
        formFieldsValue[key] = tempFieldsValue[key] === undefined ? null : tempFieldsValue[key];
      }
      delete formFieldsValue.applyTime;
    });
    return formFieldsValue;
  };

  // 切换表格展开收起
  toggleForm = () => {
    const { dispatch, expandForm } = this.props;
    dispatch({
      type: 'invoice/updateModalData',
      payload: {
        expandForm: !expandForm,
      },
    });
  };

  // 点击复选框
  handleSelectRows = (selectedRows, selectedRowKeys) => {
    this.setState({ selectedRows, selectedRowKeys });
  };

  // 表格有变化：比如：切换页码
  handleStandardTableChange = (pagination, filters, sorter) => {
    const { formValues } = this.state;
    const { activeKey, dispatch } = this.props;
    const pagerArg = {
      currentPage: pagination.current,
      pageSize: pagination.pageSize,
    };
    const values = {
      ...formValues,
      pagerArg,
    };
    // 列表有排序的字段处理
    if (sorter.field) {
      let sortBy = '';
      if (sorter.order === 'ascend') {
        sortBy = 'ASC';
      } else {
        sortBy = 'DESC';
      }
      values.pageOrdBys = []; // 排序集合
      values.pageOrdBys.push({
        property: 'creTime',
        ordBy: sortBy,
      });
    }
    if (activeKey === '1') {
      dispatch({
        type: 'invoice/fetchInvRecordList',
        payload: {
          ...values,
        },
      });
    } else {
      dispatch({
        type: 'invoice/fetchInvRuleList',
        payload: values,
      });
    }
  };

  // 重置
  resetSearch = () => {
    const { form, dispatch } = this.props;
    dispatch({
      type: 'invoice/updateModalData',
      payload: { formFieldsValue: {} },
    });
    form.resetFields();
    form.setFieldsValue({ applyTime: null });
  };

  // 切换页签
  changeTabPane = activeKey => {
    const { dispatch, formFieldsValue } = this.props;
    this.resetSearch();
    router.push(`/fmmanage/invoice/index?activeKey=${activeKey}`);
    dispatch({
      type: 'invoice/updateModalData',
      payload: {
        activeKey,
        formFieldsValue: {
          ...formFieldsValue,
        },
      },
    });
    this.setState({ selectedRows: [], selectedRowKeys: [] }, () => {
      this.searchList(this.processFormData(formFieldsValue), activeKey);
    });
  };

  // 申请退票
  applyRefundInv = invApplyId => {
    this.setState({ modalVisible: true, invApplyId });
  };

  // 取消申请退票弹框
  applyRefundCancel = flag => {
    this.setState({ modalVisible: flag });
  };

  // 申请退票提交
  applyRefundSubmit = values => {
    const {
      dispatch,
      pageData: { pagination },
      activeKey,
      formFieldsValue,
    } = this.props;
    this.callbackFn(true);
    dispatch({
      type: 'invoice/refuseInvSubmit',
      payload: {
        ...values,
      },
    }).then(response => {
      if (response.success) {
        this.callbackFn(false);
        message.success('退票成功！');
        this.applyRefundCancel(false);
        this.searchList(
          this.processFormData(formFieldsValue),
          activeKey,
          pagination.current,
          pagination.pageSize
        );
      } else {
        this.callbackFn(false);
        message.warning(response.message || '退票错误：服务端错误');
      }
    });
  };

  // 控制模态框确定按钮loading
  callbackFn = flag => {
    this.setState({ loadingFlag: flag });
  };

  // 复制
  goCopy = () => {
    const { selectedRowKeys } = this.state;
    if (selectedRowKeys.length > 0 && selectedRowKeys.length === 1) {
      router.push(`/fmmanage/invoice/editinvrule?invRuleId=${selectedRowKeys[0]}&isUpdate=false`);
    } else {
      message.warning(`请选择一条数据`);
    }
  };

  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
    } = this.props;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '12px 0 0 0' }} bordered={false}>
        <Form layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    initialValue: formFieldsValue.custId,
                  })(<Customer allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="名称">
                  {getFieldDecorator('custSuppId', {
                    initialValue: formFieldsValue.custSuppId,
                  })(<CustOrSupp labelInValue allowClear />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="发票状态">
                  {getFieldDecorator('invState', {
                    initialValue: formFieldsValue.invState,
                  })(<DictCode dictType="FM_INV_STATE" allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="合同名称">
                  {getFieldDecorator('contId', {
                    initialValue: formFieldsValue.contId,
                  })(<CustSuppCont allowClear params={{ contType: 3, contState: 2 }} />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              <span>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={() => this.searchBtnList(activeKey)}
                >
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                {activeKey === '1' ? (
                  <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                    展开 <DownOutlined />
                  </a>
                ) : null}
              </span>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  renderAdvancedForm() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
    } = this.props;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '12px 0 0 0' }} bordered={false}>
        <Form layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="客户名称">
                  {getFieldDecorator('custId', {
                    initialValue: formFieldsValue.custId,
                  })(<Customer allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="名称">
                  {getFieldDecorator('custSuppId', {
                    initialValue: formFieldsValue.custSuppId,
                  })(<CustOrSupp labelInValue allowClear />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="发票状态">
                  {getFieldDecorator('invState', {
                    initialValue: formFieldsValue.invState,
                  })(<DictCode dictType="FM_INV_STATE" allowClear />)}
                </FormItem>
              ) : (
                <FormItem {...this.tableSearchLayout} label="合同名称">
                  {getFieldDecorator('contId', {
                    initialValue: formFieldsValue.contId,
                  })(<CustSuppCont allowClear params={{ contType: 3, contState: 2 }} />)}
                </FormItem>
              )}
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="申请时间">
                  {getFieldDecorator('applyTime', {
                    initialValue: formFieldsValue.applyTime,
                  })(
                    <RangePicker
                      placeholder={['开始日期', '结束日期']}
                      style={{ width: '100%' }}
                      format="YYYY-MM-DD"
                    />
                  )}
                </FormItem>
              ) : (
                <span>
                  <Button
                    type="primary"
                    htmlType="submit"
                    onClick={() => this.searchBtnList(activeKey)}
                  >
                    查询
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                    重置
                  </Button>
                </span>
              )}
            </Col>
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            {activeKey === '1' ? (
              <Fragment>
                <Col md={8} sm={24}>
                  <FormItem {...this.tableSearchLayout} label="发票类型">
                    {getFieldDecorator('invRuleType', {
                      initialValue: formFieldsValue.invRuleType,
                    })(<DictCode dictType="FM_INV_RULE_TYPE" allowClear />)}
                  </FormItem>
                </Col>
                <Col md={8} sm={24} />
                <Col md={8} sm={24}>
                  <span style={{ float: 'right', marginBottom: 12 }}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      onClick={() => this.searchBtnList(activeKey)}
                    >
                      查询
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                      重置
                    </Button>
                    <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                      收起
                      <UpOutlined />
                    </a>
                  </span>
                </Col>
              </Fragment>
            ) : null}
          </Row>
        </Form>
      </Card>
    );
  }

  renderSimpleFormNs() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
      supplyList,
    } = this.props;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '12px 0 0 0' }} bordered={false}>
        <Form layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              <FormItem label="签约方" {...this.tableSearchLayout}>
                {getFieldDecorator('custSuppId', {
                  initialValue: formFieldsValue.custSuppId,
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    showSearch
                    optionFilterProp="children"
                    notFoundContent="暂无数据"
                    allowClear
                  >
                    {supplyList.map(item => (
                      <Option key={item.suppId} title={item.name}>
                        {item.name}
                      </Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="发票状态">
                  {getFieldDecorator('invState', {
                    initialValue: formFieldsValue.invState,
                  })(<DictCode dictType="FM_INV_STATE" allowClear />)}
                </FormItem>
              ) : null}
            </Col>
            <Col md={8} sm={24}>
              <span>
                <Button
                  type="primary"
                  htmlType="submit"
                  onClick={() => this.searchBtnList(activeKey)}
                >
                  查询
                </Button>
                <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                  重置
                </Button>
                {activeKey === '1' ? (
                  <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                    展开 <DownOutlined />
                  </a>
                ) : null}
              </span>
            </Col>
          </Row>
        </Form>
      </Card>
    );
  }

  renderAdvancedFormNs() {
    const {
      form: { getFieldDecorator },
      activeKey,
      formFieldsValue,
      supplyList,
    } = this.props;
    return (
      <Card style={{ backgroundColor: '#fafafa', padding: '12px 0 0 0' }} bordered={false}>
        <Form layout="inline">
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            <Col md={8} sm={24}>
              <FormItem label="签约方" {...this.tableSearchLayout}>
                {getFieldDecorator('custSuppId', {
                  initialValue: formFieldsValue.custSuppId,
                })(
                  <HOCSelect
                    placeholder="请输入关键字检索"
                    showSearch
                    optionFilterProp="children"
                    notFoundContent="暂无数据"
                    allowClear
                  >
                    {supplyList.map(item => (
                      <Option key={item.suppId} title={item.name}>
                        {item.name}
                      </Option>
                    ))}
                  </HOCSelect>
                )}
              </FormItem>
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="发票状态">
                  {getFieldDecorator('invState', {
                    initialValue: formFieldsValue.invState,
                  })(<DictCode dictType="FM_INV_STATE" allowClear />)}
                </FormItem>
              ) : null}
            </Col>
            <Col md={8} sm={24}>
              {activeKey === '1' ? (
                <FormItem {...this.tableSearchLayout} label="申请时间">
                  {getFieldDecorator('applyTime', {
                    initialValue: formFieldsValue.applyTime,
                  })(
                    <RangePicker
                      placeholder={['开始日期', '结束日期']}
                      style={{ width: '100%' }}
                      format="YYYY-MM-DD"
                    />
                  )}
                </FormItem>
              ) : (
                <span>
                  <Button
                    type="primary"
                    htmlType="submit"
                    onClick={() => this.searchBtnList(activeKey)}
                  >
                    查询
                  </Button>
                  <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                    重置
                  </Button>
                </span>
              )}
            </Col>
          </Row>
          <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
            {activeKey === '1' ? (
              <Fragment>
                <Col md={8} sm={24} />
                <Col md={8} sm={24} />
                <Col md={8} sm={24}>
                  <span style={{ float: 'right', marginBottom: 12 }}>
                    <Button
                      type="primary"
                      htmlType="submit"
                      onClick={() => this.searchBtnList(activeKey)}
                    >
                      查询
                    </Button>
                    <Button style={{ marginLeft: 8 }} onClick={this.resetSearch}>
                      重置
                    </Button>
                    <a style={{ marginLeft: 8 }} onClick={this.toggleForm}>
                      收起
                      <UpOutlined />
                    </a>
                  </span>
                </Col>
              </Fragment>
            ) : null}
          </Row>
        </Form>
      </Card>
    );
  }

  renderForm() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedForm() : this.renderSimpleForm();
  }

  renderFormNs() {
    const { expandForm } = this.props;
    return expandForm ? this.renderAdvancedFormNs() : this.renderSimpleFormNs();
  }

  render() {
    const { pageData, loading, tabList, activeKey } = this.props;
    const {
      selectedRows,
      selectedRowKeys,
      modalVisible,
      loadingFlag,
      sysCode,
      invApplyId,
    } = this.state;

    const invRecordColumns = [
      {
        title: sysCode === 1 ? '客户名称' : '签约方',
        dataIndex: 'custSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: '开票金额（元）',
        dataIndex: 'invAmount',
        align: 'right',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => <span>{val === 0 ? 0 : (val && val) || '--'}</span>,
      },
      {
        title: '开票张数',
        dataIndex: 'invMany',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '发票状态',
        dataIndex: 'invStateName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '申请人',
        dataIndex: 'creName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '申请时间',
        dataIndex: 'creTime',
        align: 'center',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => {
          // 根据发票状态 待开票 可取消申请
          if (record.invState && record.invState === 1) {
            return (
              <span>
                <a
                  onClick={() =>
                    router.push(
                      `/fmmanage/invoice/invrecorddetail?type=1&invApplyId=${record.invApplyId}`
                    )
                  }
                >
                  查看
                </a>
                <Authorized authority="business:invoice:cancelApply" noMatch={null}>
                  <Divider type="vertical" />
                </Authorized>
                <Authorized authority="business:invoice:cancelApply" noMatch={null}>
                  <a
                    onClick={() =>
                      router.push(
                        `/fmmanage/invoice/invrecorddetail?type=2&invApplyId=${record.invApplyId}`
                      )
                    }
                  >
                    取消申请
                  </a>
                </Authorized>
              </span>
            );
          }
          if (record.invState && record.invState === 3) {
            // 已领取 可申请退票
            return (
              <span>
                <a
                  onClick={() =>
                    router.push(
                      `/fmmanage/invoice/invrecorddetail?type=1&invApplyId=${record.invApplyId}`
                    )
                  }
                >
                  查看
                </a>
                {checkPermissions('business:invoice:refundInvoice') && <Divider type="vertical" />}
                {checkPermissions('business:invoice:refundInvoice') && (
                  <Dropdown
                    overlay={
                      <Menu>
                        {checkPermissions('business:invoice:refundInvoice') && (
                          <Menu.Item onClick={() => this.applyRefundInv(record.invApplyId)}>
                            退票
                          </Menu.Item>
                        )}
                      </Menu>
                    }
                  >
                    <a>
                      更多 <DownOutlined />
                    </a>
                  </Dropdown>
                )}
              </span>
            );
          }
          return (
            <a
              onClick={() =>
                router.push(
                  `/fmmanage/invoice/invrecorddetail?type=1&invApplyId=${record.invApplyId}`
                )
              }
            >
              查看
            </a>
          );
        },
      },
    ];
    const invRuleColumns = [
      {
        title: sysCode === 1 ? '客户/供应商名称' : '签约方',
        dataIndex: 'custSuppName',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: text => <TextOverFlow text={text} />,
      },
      {
        title: sysCode === 1 ? '合同名称' : null,
        dataIndex: sysCode === 1 ? 'contName' : null,
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '服务类型',
        dataIndex: 'serTypeName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bolder' } }),
        render: val => val || '--',
      },
      {
        title: '更新人员',
        dataIndex: 'creName',
        align: 'center',
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => val || '--',
      },
      {
        title: '更新时间',
        dataIndex: 'creTime',
        align: 'center',
        sorter: (a, b) => new Date(b.creTime) - new Date(a.creTime),
        onHeaderCell: () => ({ style: { fontWeight: 'bold' } }),
        render: val => (val && moment(val).format('YYYY-MM-DD HH:mm')) || '--',
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onHeaderCell: () => ({ style: { fontWeight: 'bold', width: 150, textAlign: 'center' } }),
        onCell: () => ({ style: { textAlign: 'center' } }),
        render: (text, record) => (
          <span>
            <a
              onClick={() =>
                router.push(`/fmmanage/invoice/invruledetail?invRuleId=${record.invRuleId}`)
              }
            >
              查看
            </a>
            {checkPermissions([
              'business:invoice:updateInvoiceRule',
              'business:invoice:costCenterInvoiceRule',
            ]) && <Divider type="vertical" />}
            {checkPermissions([
              'business:invoice:updateInvoiceRule',
              'business:invoice:costCenterInvoiceRule',
            ]) && (
              <Dropdown
                overlay={
                  <Menu>
                    {checkPermissions('business:invoice:updateInvoiceRule') && (
                      <Menu.Item
                        onClick={() =>
                          router.push(
                            `/fmmanage/invoice/editinvrule?invRuleId=${
                              record.invRuleId
                            }&isUpdate=true`
                          )
                        }
                      >
                        修改
                      </Menu.Item>
                    )}
                    {checkPermissions('business:invoice:costCenterInvoiceRule') && (
                      <Menu.Item
                        onClick={() =>
                          router.push(
                            `/fmmanage/invoice/costcenter?invRuleId=${
                              record.invRuleId
                            }&custSuppId=${record.custSuppId}`
                          )
                        }
                      >
                        成本中心发票设置
                      </Menu.Item>
                    )}
                  </Menu>
                }
              >
                <a>
                  更多 <DownOutlined />
                </a>
              </Dropdown>
            )}
          </span>
        ),
      },
    ];
    const invoiceRecord = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Authorized authority="business:invoice:cust" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              onClick={() => router.push(`/fmmanage/invoice/openinv?invoice=1`)}
            >
              客户开票申请
            </Button>
          </Authorized>
          <Authorized authority="business:invoice:supp" noMatch={null}>
            <Button
              style={{ marginRight: '8px' }}
              onClick={() => router.push(`/fmmanage/invoice/openinv?invoice=2`)}
            >
              供应商开票申请
            </Button>
          </Authorized>
          <Authorized authority="business:invoice:sendSupp" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              onClick={() => router.push(`/fmmanage/invoice/openinv?invoice=3`)}
            >
              开票申请
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="invApplyId"
          columns={invRecordColumns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    const billingRule = (
      <div>
        <Row style={{ marginBottom: '16px' }}>
          <Authorized authority="business:invoice:addInvoiceRule" noMatch={null}>
            <Button
              type="primary"
              style={{ marginRight: '8px' }}
              onClick={() => router.push('/fmmanage/invoice/editinvrule')}
            >
              新增发票规则
            </Button>
          </Authorized>
          <Authorized authority="business:invoice:copyInvoiceRule" noMatch={null}>
            <Button style={{ marginRight: '8px' }} onClick={() => this.goCopy()}>
              复制
            </Button>
          </Authorized>
        </Row>
        <StandardTable
          selectedRows={selectedRows}
          selectedRowKeys={selectedRowKeys}
          loading={loading}
          data={pageData}
          rowKey="invRuleId"
          columns={invRuleColumns}
          onSelectRow={this.handleSelectRows}
          onChange={this.handleStandardTableChange}
        />
      </div>
    );
    // 获取页签组件
    const getTabPane = key => {
      switch (key) {
        case '1':
          return invoiceRecord;
        case '2':
          return billingRule;
        default:
          return <div />;
      }
    };
    return (
      <PageHeaderWrapper>
        <Card className={styles.tabCard} bordered={false}>
          <Tabs activeKey={activeKey} onChange={this.changeTabPane}>
            {tabList.map(pane => (
              <TabPane tab={pane.itemName} key={pane.itemCode}>
                <div className={styles.tableListForm}>
                  {sysCode === 1 ? this.renderForm() : this.renderFormNs()}
                </div>
                {getTabPane(pane.itemCode)}
              </TabPane>
            ))}
          </Tabs>
        </Card>
        {/* 申请退票弹框 */}
        <RefundModal
          modalVisible={modalVisible}
          onCancel={() => this.applyRefundCancel(false)}
          onOk={this.applyRefundSubmit}
          loadingFlag={loadingFlag}
          invApplyId={invApplyId}
        />
      </PageHeaderWrapper>
    );
  }
}
export default TableList;
